﻿using UnityEngine;
using System.Collections;
using TableProto;
using UnityEngine.UI;
using System.Collections.Generic;
using DG.Tweening;

/// <summary>
/// ShoppingListPanel  UI 
/// </summary>
public class ShoppingListController : Singleton<ShoppingListController>
{    
    public ShoppingListView _view;
    //-18.4   -22  -25.73  -29.61
    //- 0.12   -7.43    -11    -14.23
    private float[] mainCamPosRightX = new float[7] { -0.12f, -7.11f, -10.7156f, -14.1884f, -18f, -21.62f, -25.55f };
    //private float[] mainCamPosLeftX = new float[4] { -0.12f, -7.11f, -10.7156f, -14.1884f };
    //对应的资源id
    private List<string> atlasId = new List<string>();
     
    public override void Init()
    {
        base.Init();        
        _view = new ShoppingListView();       
    }
    Image[] imgs;
    Image[] imgList;
    string guidSound;
    /// <summary>
    /// 设置需要购买的物品信息
    /// </summary>
    void SetBuyList()
    {
        if (PlaceGoods.Instance.goodsBuyList != null)
        {
            imgs = new Image[] { _view.buy1, _view.buy2, _view.buy3, _view.buy4, _view.buy5, _view.buy6 };
            imgList = new Image[] { _view.list1_btn.GetComponent<Image>(), _view.list2_btn.GetComponent<Image>(), _view.list3_btn.GetComponent<Image>(), _view.list4_btn.GetComponent<Image>(), _view.list5_btn.GetComponent<Image>(), _view.list6_btn.GetComponent<Image>() };
            SuperMarketGoodsInfo smgi = new SuperMarketGoodsInfo();

            //Debug.Log(PlaceGoods.Instance.goodsBuyList.Count + "  ==== goodsBuyList Count ");
            atlasId.Clear();
            for (int i = 0; i < PlaceGoods.Instance.goodsBuyList.Count; i++)
            {
                smgi = GoodsInfoModel.Instance.GetModelByResId(PlaceGoods.Instance.goodsBuyList[i]);
                atlasId.Add(smgi.resid);
                _view.finishState_obj[i].SetActive(false);
                //Debug.Log(smgi.atlas);
                //Debug.Log(i + "  === smgi.atlas ");
                Sprite tempSprite = CommonUtility.GetSprite(emUIAltas.SuperMarketAtlas, smgi.atlas);
                imgs[i].transform.parent.gameObject.SetActive(true);
                imgs[i].sprite = tempSprite;
                imgs[i].SetNativeSize();
                imgList[i].transform.parent.gameObject.SetActive(true);
                imgList[i].sprite = tempSprite;
                imgList[i].SetNativeSize();

                if (i == 0)
                {
                    guidSound = smgi.sound;
                    _view.guid_img.sprite = tempSprite;
                    _view.guid_img.SetNativeSize();
                }
            }
            if (PlaceGoods.Instance.goodsBuyList.Count < 6)
            {
                for (int i = PlaceGoods.Instance.goodsBuyList.Count; i < 6; i++)
                {
                    imgList[i].transform.parent.gameObject.SetActive(false);
                }
            }
        }
    }

    public override void UnInit()
    {
        base.UnInit();
    }

    public void OpenView()
    {
        SuperMarketGame.Instance.IsCheckShopPanel = true;
        _view.OpenForm();
        
        RegisterEvent();

        //设置清单图片
        SetBuyList();
    }
    /// <summary>
    /// 设置物品购买状态 
    /// </summary>
    /// <param name="name"></param>
    /// <param name="active"></param>
    public void SetBuyState(string name,bool active)
    {
        for (int i = 0; i < atlasId.Count; i++)
        {
            if (atlasId[i] == name)
            {
                _view.finishState_obj[i].SetActive(active);
                //SortState(i);
                break;
            }
        }
        if (PlaceGoods.Instance.goodsBuyList.Count > 3 && _view.finishState_obj[0].activeSelf && _view.finishState_obj[1].activeSelf && _view.finishState_obj[2].activeSelf)
        {
            Canvas.ForceUpdateCanvases();
            _view.scroll.verticalNormalizedPosition = 0f;
            Canvas.ForceUpdateCanvases();
        }
    }

    public void SortState(int curIndex)
    {
        if (PlaceGoods.Instance.goodsBuyDic != null && PlaceGoods.Instance.goodsBuyDic.Count > 3)
        {
            int index = 0;
            foreach (var item in PlaceGoods.Instance.goodsBuyDic)
            {
                //已经购买完成 (暂时为1 以后可能改成多个数量)
                if (item.Value > 0)                
                    break;                
                else
                    index++;
            }
            //index - 1  和  curIndex  交换
            Sprite tempSprite = imgList[index - 1].sprite; //新的 
            imgList[index - 1].sprite = imgList[curIndex].sprite;//当前替换的
            imgList[curIndex].sprite = tempSprite;
            _view.finishState_obj[index - 1].SetActive(true);
        }      
    }

    public void CloseView()
    {
        SuperMarketGame.Instance.IsCheckShopPanel = false;
        lastType = 0;
        _view.CloseForm();
        RemoveEvent();
        //SuperMarketGame.Instance.OnExit();
        ShoppingListController.DestroyInstance();
    }

    private void RegisterEvent()
    {
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.ShopList_Btn_Bg, OnBgClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.MenuList1_Btn, OnMenuListClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.MenuList2_Btn, OnMenuListClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.MenuList3_Btn, OnMenuListClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.MenuList4_Btn, OnMenuListClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.MenuList5_Btn, OnMenuListClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.MenuList6_Btn, OnMenuListClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Return_Btn, OnReturnClick);
        HUIEventManager.Instance.AddUIEventListener(enUIEventID.Guid_Btn, OnGuidClick);
    }

    private void RemoveEvent()
    {
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.ShopList_Btn_Bg, OnBgClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.MenuList1_Btn, OnMenuListClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.MenuList2_Btn, OnMenuListClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.MenuList3_Btn, OnMenuListClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.MenuList4_Btn, OnMenuListClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.MenuList5_Btn, OnMenuListClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.MenuList6_Btn, OnMenuListClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Return_Btn, OnReturnClick);
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Guid_Btn, OnGuidClick);
    }

    public void OnBgClick(HUIEvent e)
    {
        SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_601010403);
        SuperMarketGame.Instance.IsCheckShopPanel = false;
        //Debug.Log(" OnBgClick  ");
        Animation ani = _view.BgBtn.GetComponent<Animation>();
        TimerManager.Instance.AddTimer(1f, () =>        {
            //CloseView();
            if (_view.BgBtn != null)
                _view.BgBtn.SetActive(false);           
        });
        TimerManager.Instance.AddTimer(0.5f, () => { _view.menuList_obj.SetActive(true); });
        ani.Play("shoplistmove");
        //SuperMarketGame.Instance.DragScceneEnable(true);
        SuperMarketGame.Instance.CarShakeEnabel(true);
    }

    public int lastType = 0;
    /// <summary>
    /// 左侧菜单点击
    /// </summary>
    /// <param name="e"></param>
    void OnMenuListClick(HUIEvent e)
    {
        //Debug.Log(SuperMarketGame.Instance.isCanDragScene.ToString() + "  == SuperMarketGame.Instance.isCanDragScene)  ");
        if (!SuperMarketGame.Instance.isCanDragScene) return;
        //Debug.Log((int)e.m_eventID + "  == OnMenuListClick  ");
        SuperMarketGoodsInfo smgi = null;
        switch (e.m_eventID)
        {
            case enUIEventID.MenuList1_Btn:
                smgi = GoodsInfoModel.Instance.GetModelByResId(PlaceGoods.Instance.goodsBuyList[0]);
                break;
            case enUIEventID.MenuList2_Btn:
                smgi = GoodsInfoModel.Instance.GetModelByResId(PlaceGoods.Instance.goodsBuyList[1]);
                break;
            case enUIEventID.MenuList3_Btn:
                smgi = GoodsInfoModel.Instance.GetModelByResId(PlaceGoods.Instance.goodsBuyList[2]);
                break;
            case enUIEventID.MenuList4_Btn:
                smgi = GoodsInfoModel.Instance.GetModelByResId(PlaceGoods.Instance.goodsBuyList[3]);
                break;
            case enUIEventID.MenuList5_Btn:
                smgi = GoodsInfoModel.Instance.GetModelByResId(PlaceGoods.Instance.goodsBuyList[4]);
                break;
            case enUIEventID.MenuList6_Btn:
                smgi = GoodsInfoModel.Instance.GetModelByResId(PlaceGoods.Instance.goodsBuyList[5]);
                break;
        }
        if (lastType == smgi.type) return;
        if (e.m_eventID != enUIEventID.MenuList1_Btn)
        {
            //Debug.Log("OnMenuListClick  =====");
            SuperMarketGame.Instance.guidWay = false;
            WayPointEnable(false);
        }
        float during = 0.5f;
        if (lastType != 0)
        {
            during = Mathf.Abs(smgi.type - lastType) * 0.5f;
        }
        lastType = smgi.type;
        //Debug.Log(SuperMarketGame.Instance.RoleRotate + "  === SuperMarketGame.Instance.RoleRotate");         
        //float targetPosition = GameObject.Find(smgi.groupId+"(Clone)").transform.position.x;
        //Debug.Log(targetPosition + "  === targetPosition");
        //if (targetPosition < RoleInSuperMarketCtrl.Instance.transform.position.x)
        //{
        SuperMarketGame.Instance.MoveMainCamera(mainCamPosRightX[smgi.type], null, 0, 0, during);
       // }
        //else
        //{
            //SuperMarketGame.Instance.MoveMainCamera(mainCamPosLeftX[smgi.type], null, 0, 0, 0.5f);
        //}

        //播放声音
        SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.SOUND+smgi.sound);
        /*switch ((GoodsType)smgi.type)
        {
            case GoodsType.Vegetables:
                break;
            case GoodsType.Fruits:
                break;
            case GoodsType.Snacks:
                break;             
        }  */
    }

    void OnReturnClick(HUIEvent e)
    {
        //SuperMarketGame.Instance.IsCheckShopPanel = false;
        HUIEventManager.Instance.RemoveUIEventListener(enUIEventID.Return_Btn, OnReturnClick);
        TimerManager.Instance.RemoveAllTimer();
        //Debug.LogError("  OnReturnClick == ");
        Input.multiTouchEnabled = true;
        GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
    }

    public void WayPointEnable(bool isActive)
    {
        if (_view.m_Form == null) return;
        if (isActive)
        {
            for (int i = 0; i < _view.way_obj.transform.childCount; i++)
            {
                _view.way_obj.transform.GetChild(i).GetComponent<WayGuide>().isChange = true;
            }
        }           
        else
        {
            for (int i = 0; i < _view.way_obj.transform.childCount; i++)
            {
                _view.way_obj.transform.GetChild(i).GetComponent<WayGuide>().isChange = false;
            }
        }
        _view.way_obj.SetActive(isActive);
    }

    public bool WayPointState()
    {
        return _view.way_obj !=null && _view.way_obj.activeSelf;
    }

    public void EnableGuid(bool isActive)
    {
        _view.guid_obj.SetActive(isActive);
        if (isActive)
        {
            _view.finger_obj.transform.DOLocalRotate(new Vector3(40,0,0),0.5f).SetEase(Ease.Linear).SetLoops<Tweener>(-1, LoopType.Yoyo);
        }
        else
        {
            _view.finger_obj.transform.DOKill();
        }       
    }

    public void OnGuidClick(HUIEvent e)
    {
        AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SuperMarketResPath.Sound_404050350));
        EnableGuid(false);
        SuperMarketGame.Instance.MoveMainCamera(mainCamPosRightX[1], ()=> {
            SuperMarketGame.Instance.IsCheckOperate = true;  
            SuperMarketGame.Instance.guidTotalCount = SuperMarketGame.Instance.heartTimeCheck;
        }, 0, 0, 0.5f);
        //播放声音
        SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.SOUND + guidSound);
    }
}